package com.tlb.springboot.starter.rocketmq.config;

import com.aliyun.openservices.shade.com.alibaba.rocketmq.client.exception.MQClientException;
import com.tlb.springboot.starter.rocketmq.impl.RocketMQProducer;
import com.tlb.springboot.starter.rocketmq.util.AliAddressUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.UUID;

/**
 * @author yuaneg 2018/9/4
 */
@Slf4j
public class RocketMQProducerBeanPostProcessor implements BeanPostProcessor {

    private static final String DEFAULT_GROUP = "DEFAULT_PRODUCER";

    private RocketMqProperties properties;

    public RocketMQProducerBeanPostProcessor(RocketMqProperties properties) {
        this.properties = properties;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RocketMQProducer) {
            RocketMQProducer producer = (RocketMQProducer) bean;
            if (null != properties.getSessionCredentials()) {
                producer.setNamesrvAddr(AliAddressUtil.fetchNSAddr(properties.getNameServer()));
            } else {
                producer.setNamesrvAddr(properties.getNameServer());
            }
            if (DEFAULT_GROUP.equals(producer.getProducerGroup())) {
                producer.setProducerGroup(properties.getProducer().getDefaultGroup());
            }
            producer.setVipChannelEnabled(false);
            producer.setSendMessageWithVIPChannel(false);
            producer.setSendMsgTimeout(properties.getProducer().getSendMsgTimeout());
            producer.setRetryTimesWhenSendFailed(properties.getProducer().getRetryTimesWhenSendFailed());
            producer.setRetryTimesWhenSendAsyncFailed(properties.getProducer().getRetryTimesWhenSendAsyncFailed());
            producer.setMaxMessageSize(properties.getProducer().getMaxMessageSize());
            producer.setCompressMsgBodyOverHowmuch(properties.getProducer().getCompressMsgBodyOverHowMuch());
            producer.setRetryAnotherBrokerWhenNotStoreOK(properties.getProducer().isRetryAnotherBrokerWhenNotStoreOk());
            producer.setInstanceName(UUID.randomUUID().toString());
            try {
                producer.start();
                log.debug("rocketMq producer start success");
            } catch (MQClientException e) {
                log.error("rocketMq producer start error", e);
            }
        }
        return bean;
    }
}
